"""
Case Type   : Timescaledb功能测试
Case Name   : 无表时确保drop_chunks成功且show_chunks与drop_chunks的回显信息相同
Create At   : 2025/05/13
Owner       : lihongji
Description :
              1.show_chunks展示早于1小时的数据块(早于1小时本身无数据块)
              2.drop_chunks删除早于1小时的数据块(早于1小时本身无数据块)
Expect      :
              1.无数据返回
              2.无数据返回
History     :
"""

import unittest
import os

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node


class Timescaledb(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.constant = Constant()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.Constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbPGmode')
        self.db_user_node = Node(node='PrimaryDbPGmode')
        status = self.primary_sh.get_db_cluster_status()
        self.assertTrue("Normal" in status or "Degraded" in status)
        select_extension_cmd = f"SELECT * FROM pg_extension;"
        select_extension_result = self.primary_sh.execut_db_sql(select_extension_cmd)
        if "timescaledb" not in select_extension_result:
            create_extension_cmd = f"create extension timescaledb;"
            create_extension_result = (
                self.primary_sh.execut_db_sql(create_extension_cmd))
            self.assertIn(self.constant.extension_create_success,
                          create_extension_result, '创建timescaledb扩展失败')

    def test_add_dimension(self):
        text = ('----step1: show_chunks展示早于1小时的数据块(早于1小时本身无数据块)'
                ' expect: 无数据返回----')
        self.log.info(text)
        show_chunks = "SELECT show_chunks(older_than => INTERVAL '1 hour');"
        show_chunks_result = self.primary_sh.execut_db_sql(show_chunks)
        self.log.info(show_chunks_result)
        self.assertIn('(0 rows)', show_chunks_result, '执行失败' + text)

        text = ('----step2: drop_chunks删除早于1小时的数据块(早于1小时本身无数据块) '
                'expect: 无数据返回----')
        self.log.info(text)
        drop_chunks = "SELECT drop_chunks(INTERVAL '1 hour', verbose => true);"
        drop_chunks_result = self.primary_sh.execut_db_sql(drop_chunks)
        self.log.info(drop_chunks_result)
        self.assertIn('(0 rows)', drop_chunks_result, '执行失败' + text)

    def tearDown(self):
        self.log.info("无存留信息，不清理环境")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
